<script setup>
import { ref, reactive } from 'vue'
import { User, Lock, Message, Check } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 当前步骤
const currentStep = ref(1)

// 定义数据模型
const registerData = reactive({
  email: '',
  code: '',
  username: '',
  password: '',
  confirmPassword: '',
  pictureCode: '' // 图形验证码
})

// 表单引用
const registerFormRef = ref(null)
const emailFormRef = ref(null)
const accountFormRef = ref(null)

// 验证码倒计时
const countdown = ref(0)
const countdownTimer = ref(null)
// 标记是否可以发送验证码
const canSendCode = ref(true)
// 注册成功后自动跳转倒计时
const autoRedirectCountdown = ref(0)
const autoRedirectTimer = ref(null)

// 图形验证码相关状态
const captchaDialogVisible = ref(false) // 控制图形验证码弹窗显示
const captchaImageUrl = ref('') // 存储验证码图片URL
const currentEmailForCaptcha = ref('') // 存储当前邮箱

// 协议同意状态
const agreed = ref(false)

// 定义验证规则
// 用户名为1~16位非空字符
// 密码为5~16位非空字符
// 邮箱为非空字符且为邮箱格式
// 验证码为4位非空字符
// 图形验证码为4位数字
const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
  ],
  pictureCode: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '图形验证码长度为4位', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '图形验证码必须为4位数字', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 16, message: '用户名长度为1~16位字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5~16位字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerData.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取验证码
const getCode = async () => {
  // 如果不能发送验证码，直接返回
  if (!canSendCode.value) {
    return
  }
  
  if (!registerData.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerData.email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }
  
  // 显示图形验证码弹窗
  captchaDialogVisible.value = true
  currentEmailForCaptcha.value = registerData.email
  
  try {
    // 获取图形验证码图片URL
    const timestamp = Date.now()
    captchaImageUrl.value = getCaptchaService(registerData.email) + '&t=' + timestamp
    console.log('图形验证码URL:', captchaImageUrl.value)
  } catch (error) {
    console.error('获取图形验证码失败:', error)
    ElMessage.error('获取图形验证码失败')
    canSendCode.value = true
  }
}

// 处理图形验证码输入完成
const handleCaptchaComplete = async () => {
  if (!registerData.pictureCode || registerData.pictureCode.length !== 4) {
    ElMessage.warning('请输入4位图形验证码')
    return
  }
  
  // 关闭弹窗
  captchaDialogVisible.value = false
  
  try {
    console.log('准备发送验证码到邮箱:', registerData.email)
    // 调用发送验证码API，包含邮箱和图形验证码
    const result = await sendCodeService(registerData.email, registerData.pictureCode)
    console.log('验证码发送API响应:', result.data)
    
    // 检查响应是否存在
    if (!result) {
      console.error('验证码发送失败,响应为空')
      ElMessage.error('验证码发送失败，服务器无响应')
      // 发送失败时，允许重新发送
      canSendCode.value = true
      return
    }
    
    if (result.code === 0) {
      ElMessage.success('验证码已发送')
      
      // 清空图形验证码
      registerData.pictureCode = ''
      
      // 开始倒计时
      countdown.value = 120
      countdownTimer.value = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(countdownTimer.value)
          // 倒计时结束后，允许再次发送验证码
          canSendCode.value = true
        }
      }, 1000)
    } else {
      console.error('验证码发送失败，响应码:', result.code, '错误信息:', result.message)
      ElMessage.error(result.message || '验证码发送失败')
      // 发送失败时，允许重新发送
      canSendCode.value = true
      // 清空图形验证码，让用户重新输入
      registerData.pictureCode = ''
    }
  } catch (error) {
    console.error('验证码发送API调用异常:', error)
    // 检查是否为429错误
    if (error.response && error.response.status === 429) {
      ElMessage.error('验证码生成过于频繁，5分钟后重试')
    } else {
      ElMessage.error('验证码发送失败，请稍后重试')
    }
    // 发送异常时，允许重新发送
    canSendCode.value = true
    // 清空图形验证码，让用户重新输入
    registerData.pictureCode = ''
  }
}

// 刷新图形验证码
const refreshCaptchaImage = () => {
  // 添加时间戳避免缓存
  const timestamp = Date.now()
  captchaImageUrl.value = getCaptchaService(currentEmailForCaptcha.value) + '&t=' + timestamp
  console.log('刷新注册页面图形验证码，新URL:', captchaImageUrl.value)
}

// 处理图形验证码图片加载错误
const handleCaptchaImageError = async () => {
  console.error('注册页面图形验证码图片加载失败，URL:', captchaImageUrl.value)
  
  // 尝试通过fetch检查具体的错误状态码
  try {
    const response = await fetch(captchaImageUrl.value, { method: 'HEAD' })
    if (response.status === 429) {
      ElMessage.error('验证码生成过于频繁，5分钟后重试')
    } else {
      ElMessage.error('图形验证码加载失败，请重试')
    }
  } catch (fetchError) {
    // 如果fetch也失败，回退到基本错误消息
    ElMessage.error('图形验证码加载失败，请重试')
  }
}

// 处理图形验证码输入
const handleCaptchaInput = (value) => {
  // 只允许输入数字
  registerData.pictureCode = value.replace(/[^\d]/g, '')
  
  // 输入满4位自动提交
  if (registerData.pictureCode.length === 4) {
    handleCaptchaComplete()
  }
}

// 验证邮箱和验证码
const verifyEmail = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 调用验证码验证接口
        const result = await verifyCodeService(registerData.email, registerData.code)
        console.log('验证码验证结果:', result)
        agreed.value = true
        currentStep.value = 2
        
        // if (result.code === 0) {
        //   // 自动勾选协议同意
        //   agreed.value = true
        //   currentStep.value = 2
        //   ElMessage.success('邮箱验证成功')
        // } else {
        //   ElMessage.error(result.msg || '验证码验证失败')
        // }
      } catch (error) {
        console.error('验证码验证异常:', error)
        ElMessage.error('验证码验证失败，请重试')
      }
    } else {
      ElMessage.error('请检查输入信息')
    }
  })
}

import { userRegisterService, sendCodeService, verifyCodeService, getCaptchaService } from '@/api/user.ts'
import { useTokenStore } from '@/stores/token.ts'
import { useUserStore } from '@/stores/user.ts'

const tokenStore = useTokenStore()
const userStore = useUserStore()

const handleRegister = async () => {
  console.log('注册数据:', registerData); // 打印完整注册数据
  // 错误: registerData已经是响应式对象，不需要使用.value
  let result = await userRegisterService(registerData);
  if(result.code===0){
    currentStep.value = 3
    ElMessage.success(result.message?result.message:'注册成功！')
    
    // 保存用户信息和token，实现自动登录
    if (result.data && result.data.token) {
      tokenStore.setToken(result.data.token)
    }
    userStore.setUsername(registerData.username)
    
    // 开始自动跳转倒计时
    autoRedirectCountdown.value = 3
    autoRedirectTimer.value = setInterval(() => {
      autoRedirectCountdown.value--
      if (autoRedirectCountdown.value <= 0) {
        clearInterval(autoRedirectTimer.value)
        // 倒计时结束后自动跳转到登录页，传递邮箱和密码参数
        router.push({path: '/login', query: {email: registerData.email, password: registerData.password}})
      }
    }, 1000)
  } else {
    ElMessage.error(result.message?result.message:'注册失败')
  }
}

// 立即登录按钮点击事件
const goToLogin = () => {
  // 清除自动跳转倒计时
  if (autoRedirectTimer.value) {
    clearInterval(autoRedirectTimer.value)
  }
  
  // 如果已经保存了用户信息，直接跳转到主页
  if (userStore.isLoggedIn) {
    router.push('/layout')
  } else {
    // 否则跳转到登录页，传递邮箱和密码参数
    router.push({path: '/login', query: {email: registerData.email, password: registerData.password}})
  }
}

// 组件卸载时清除定时器
import { onUnmounted } from 'vue'
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
  if (autoRedirectTimer.value) {
    clearInterval(autoRedirectTimer.value)
  }
})
</script>

<template>
  <el-container class="baokede-register-page">
    <!-- 注册区域 -->
    <el-main class="main-content">
      <el-card class="register-box" :body-style="{ padding: '25px' }" shadow="always">
        <!-- 宝可得 Logo -->
        <el-row>
          <el-col :span="24">
            <h1 class="baokede-logo">宝可得</h1>
          </el-col>
        </el-row>
        
        <!-- 进度指示器 -->
        <div class="progress-indicator">
          <div class="progress-step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
            <div class="step-circle">
              <el-icon v-if="currentStep > 1"><Check /></el-icon>
              <span v-else>1</span>
            </div>
            <span class="step-text">验证邮箱</span>
          </div>
          <div class="progress-line" :class="{ active: currentStep >= 2 }"></div>
          <div class="progress-step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
            <div class="step-circle">
              <el-icon v-if="currentStep > 2"><Check /></el-icon>
              <span v-else>2</span>
            </div>
            <span class="step-text">填写账号信息</span>
          </div>
          <div class="progress-line" :class="{ active: currentStep >= 3 }"></div>
          <div class="progress-step" :class="{ active: currentStep >= 3 }">
            <div class="step-circle">
              <span>3</span>
            </div>
            <span class="step-text">注册成功</span>
          </div>
        </div>

        <!-- 第一步：邮箱验证 -->
        <div v-if="currentStep === 1" class="step-content">
          <!-- <h3 class="step-title">验证邮箱</h3> -->
          <el-form
            ref="emailFormRef"
            :model="registerData"
            :rules="{ email: rules.email, code: rules.code }"
            label-position="top"
            class="register-form"
          >
            <el-form-item prop="email">
              <el-input
                v-model="registerData.email"
                placeholder="请输入邮箱"
                :prefix-icon="Message"
              />
            </el-form-item>
            
            <el-form-item prop="code">
              <el-row :gutter="10" align="middle">
                <el-col :span="16">
                  <el-input
                    v-model="registerData.code"
                    placeholder="请输入验证码"
                    :prefix-icon="Message"
                  />
                </el-col>
                <el-col :span="8" style="display: flex; align-items: center;">
                  <el-button
                    class="get-code-button"
                    @click="getCode"
                    :disabled="countdown > 0 || !canSendCode"
                    :loading="!canSendCode && countdown === 0"
                  >
                    {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="continue-button"
                @click="verifyEmail(emailFormRef)"
              >
                同意协议并继续
              </el-button>
            </el-form-item>
            
            <!-- 协议同意选项 -->
            <div class="agreement-section">
              <el-checkbox v-model="agreed" class="agreement-checkbox">
                我已阅读并同意
                <el-link type="primary" class="agreement-link">
                  《宝可得用户服务协议和隐私政策》
                </el-link>
              </el-checkbox>
            </div>
          </el-form>
        </div>

        <!-- 第二步：填写账号信息 -->
        <div v-if="currentStep === 2" class="step-content">
          <!-- <h3 class="step-title">填写账号信息</h3> -->
          <el-form
            ref="accountFormRef"
            :model="registerData"
            :rules="{ username: rules.username, password: rules.password, confirmPassword: rules.confirmPassword }"
            label-position="top"
            class="register-form"
          >
            <el-form-item prop="username">
              <el-input
                v-model="registerData.username"
                placeholder="请输入用户名"
                :prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="registerData.password"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerData.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                class="register-button"
                @click="handleRegister()"
              >
                立即注册
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 第三步：注册成功 -->
        <div v-if="currentStep === 3" class="step-content">
          <div class="success-content">
            <div class="success-icon">
              <el-icon><Check /></el-icon>
            </div>
            <h3 class="success-title">注册成功</h3>
            <p class="success-desc">恭喜您，账号注册成功！</p>
            <p class="redirect-countdown">{{ autoRedirectCountdown }}秒后自动跳转到登录页</p>
            <el-button
              type="primary"
              class="login-button"
              @click="goToLogin"
            >
              立即进入
            </el-button>
          </div>
        </div>
        
        <!-- 图形验证码弹窗 -->
        <el-dialog
          v-model="captchaDialogVisible"
          title="人机验证"
          width="400px"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          class="captcha-dialog"
        >
          <div class="captcha-content">
            <div class="captcha-image-container">
              <img
                :src="captchaImageUrl"
                alt="图形验证码"
                class="captcha-image"
                @click="refreshCaptchaImage"
                @error="handleCaptchaImageError"
              />
            </div>
            <el-input
              v-model="registerData.pictureCode"
              placeholder="请输入图片中的4位数字"
              maxlength="4"
              @input="handleCaptchaInput"
              class="captcha-input"
            />
          </div>
        </el-dialog>
        
        <!-- 底部链接 -->
        <div class="bottom-links">
          <span class="left-link">
            已有账号？
            <el-link type="primary" @click="goToLogin">立即登录</el-link>
          </span>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<style scoped lang="scss">
.baokede-register-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.main-content {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2.5rem 0.9375rem;
}

.register-box {
  width: 25rem;
  max-width: 100%;
  border-radius: 0.75rem;
  background: white;
  box-shadow: 0 0.5rem 2rem rgba(0, 0, 0, 0.1);
  margin: 0 auto;

  :deep(.el-card__body) {
    padding: 1.5625rem;
  }
}

.baokede-logo {
  text-align: center;
  font-size: 2.25rem;
  font-weight: bold;
  color: #ee5530;
  margin-bottom: 1.5625rem;
  font-family: 'Microsoft YaHei', sans-serif;
}

// 进度指示器样式
.progress-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 1.875rem;
  
  .progress-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .step-circle {
      width: 2rem;
      height: 2rem;
      border-radius: 50%;
      background-color: #e0e0e0;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
      font-size: 0.875rem;
      font-weight: bold;
      margin-bottom: 0.5rem;
      
      &.active {
        background-color: #ee5530;
        color: white;
      }
      
      &.completed {
        background-color: #52c41a;
        color: white;
      }
    }
    
    .step-text {
      font-size: 0.75rem;
      color: #999;
      
      &.active {
        color: #ee5530;
        font-weight: bold;
      }
      
      &.completed {
        color: #52c41a;
        font-weight: bold;
      }
    }
    
    &.active {
      .step-circle {
        background-color: #ee5530;
        color: white;
      }
      
      .step-text {
        color: #ee5530;
        font-weight: bold;
      }
    }
    
    &.completed {
      .step-circle {
        background-color: #52c41a;
        color: white;
      }
      
      .step-text {
        color: #52c41a;
        font-weight: bold;
      }
    }
  }
  
  .progress-line {
    width: 3.75rem;
    height: 0.125rem;
    background-color: #e0e0e0;
    margin: 0 0.9375rem;
    margin-bottom: 1.25rem;
    
    &.active {
      background-color: #ee5530;
    }
  }
}

.step-content {
  .step-title {
    text-align: center;
    font-size: 1.25rem;
    font-weight: 600;
    color: #333;
    margin-bottom: 1.5625rem;
    font-family: 'Microsoft YaHei', sans-serif;
  }
}

.register-form {
  .el-input {
    margin: 0.1875rem 0;
  }
  
  .el-col-8, .el-col-16 {
    margin: 0.25rem 0;
  }
  

  :deep(.el-input__wrapper) {
    background-color: #fff !important;
    
    &.is-focus {
      box-shadow: 0 0 0 0.0625rem #ee5530;
      background-color: #fff !important;
    }
    
    &:hover {
      background-color: #fff !important;
    }
  }

  :deep(.el-input__inner) {
    height: 2.625rem;
    background-color: transparent !important;
    
    &:-webkit-autofill,
    &:-webkit-autofill:hover,
    &:-webkit-autofill:focus {
      -webkit-box-shadow: 0 0 0 62.5rem #fff inset !important;
      -webkit-text-fill-color: #333 !important;
      background-color: #fff !important;
    }
  }
  
  :deep(.el-input) {
    .el-input__wrapper {
      background-color: #fff !important;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 0.9375rem;
  }
   
  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
  
  .continue-button,
  .register-button {
    width: 100%;
    height: 2.625rem;
    background-color: #ee5530;
    border-color: #ee5530;
    font-size: 1rem;
    
    &:hover, &:focus {
      background-color: #d94825;
      border-color: #d94825;
    }
  }
  
  .login-button {
    width: 100%;
    height: 2.625rem;
    background-color: #ee5530;
    border-color: #ee5530;
    font-size: 1rem;
    
    &:hover, &:focus {
      background-color: #d94825;
      border-color: #d94825;
    }
  }

  .get-code-button {
    width: 100%;
    height: 2.625rem;
    background-color: #f9f9f9;
    color: #333;
    border-color: #e0e0e0;
    
    &:hover {
      background-color: #f0f0f0;
      border-color: #ccc;
    }
    
    &:disabled {
      color: #999;
      cursor: not-allowed;
    }
  }
}

.agreement-section {
  margin-top: 0.9375rem;
  text-align: center;
  
  .agreement-checkbox {
    font-size: 0.8125rem;
    color: #666;
    
    :deep(.el-checkbox__label) {
      font-size: 0.8125rem;
      color: #666;
    }
    
    :deep(.el-checkbox__input) {
      margin-right: 0.3125rem;
    }
  }
  
  .agreement-link {
    font-size: 0.8125rem;
    margin-left: 0.125rem;
    
    &:hover {
      color: #ee5530;
    }
  }
}

.success-content {
  text-align: center;
  padding: 0.9375rem 0;
  margin-top: -1.25rem;
  
  .success-icon {
    width: 3.75rem;
    height: 3.75rem;
    border-radius: 50%;
    background-color: #52c41a;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 0.9375rem;
    
    .el-icon {
      font-size: 1.875rem;
      color: white;
    }
  }
  
  h3, .success-title {
    font-size: 1.25rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 0.5rem;
  }
  
  p, .success-desc {
    color: #666;
    margin-bottom: 0.9375rem;
    font-size: 0.875rem;
  }
  
  .redirect-countdown {
    color: #ff6a00;
    font-size: 0.875rem;
    margin-bottom: 0.9375rem;
  }
  
  .login-button {
    width: 100%;
    height: 2.625rem;
    background-color: #ee5530;
    border-color: #ee5530;
    font-size: 1rem;
    margin-bottom: 0;
    
    &:hover, &:focus {
      background-color: #d94825;
      border-color: #d94825;
    }
  }
}

.bottom-links {
  display: flex;
  justify-content: center;
  margin-top: 1.25rem;
  width: 100%;
  
  .left-link {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 0.8125rem;
    
    .el-link {
      margin-left: 0.3125rem;
      font-size: 0.8125rem;
    }
  }
}

/* 响应式调整 */
@media (max-width: 48rem) {
  .register-box {
    width: 90%;
  }
  
  .register-form {
    :deep(.el-input__inner),
    .get-code-button,
    .register-button,
    .login-button {
      height: 2.375rem;
    }
  }
}

/* 图形验证码弹窗样式 */
.captcha-dialog {
    /* 确保弹窗在页面中央 */
    :deep(.el-dialog__wrapper) {
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: 2001;
    }
    
    :deep(.el-dialog) {
      margin: 0 !important;
      display: flex;
      flex-direction: column;
    }
    
    :deep(.el-dialog__body) {
      padding: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    
    .captcha-content {
      text-align: center;
      width: 100%;
    }
    
    .captcha-image-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
      width: 100%;
    }
    
    .captcha-image {
      width: 120px;
      height: 40px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      object-fit: contain;
    }
    
    .captcha-input {
      width: 200px;
      margin: 0 auto;
    }
    
    /* 响应式调整 */
    @media (max-width: 48rem) {
      :deep(.el-dialog) {
        width: 90% !important;
        max-width: 22.5rem;
      }
      
      .captcha-image {
        width: 100px;
        height: 35px;
      }
      
      .captcha-input {
        width: 180px;
      }
    }
  }
</style>